package org.eng2.model;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

public class PedidoDAO {
	
	protected boolean insert(Pedido pedido) {
		try {
			PreparedStatement ps = DataBase.getConnectionDB().
				prepareStatement("insert into pedido(data_criacao, status, conta_id)"
						+ " values(?, ?, ?, ?, ?)");
			
			ps.setDate(1, pedido.getData_criacao());
			ps.setString(2, pedido.getStatus());
			ps.setInt(3, pedido.getConta_id());
			ps.execute();
			
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
		
	}
	
	protected boolean update(Pedido pedido) {
		PreparedStatement ps;
		try {
			ps = DataBase.getConnectionDB().
				prepareStatement("update pedido set data_criacao=?, status=?, conta_id=?"
					+ " where id=?");
			
			ps.setDate(1, pedido.getData_criacao());
			ps.setString(2, pedido.getStatus());
			ps.setInt(3, pedido.getConta_id());
			ps.execute();
			
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return false;
	}
	
	protected Pedido getOne(int id) throws SQLException {
		PreparedStatement ps;
		Pedido i = null;
		
		try {
			ps = DataBase.getConnectionDB().
					prepareStatement("select * from pedido where id=?");
			
			ps.setInt(1, id);
			
			ResultSet rs = ps.executeQuery();
			
			if (rs.next()) {
				i = new Pedido();
				
				i.setId(id);
				i.setData_criacao(rs.getDate("data_criacao"));
				i.setStatus(rs.getString("status"));
				i.setConta_id(rs.getInt("conta_id"));
			}
		} catch (Exception e) {}
		
		return i;
	}
	
	protected ArrayList<Pedido> getAll() throws SQLException {
		PreparedStatement ps;
		Pedido i = null;
		ArrayList<Pedido> pedidos = null;
		
		try {
			ps = DataBase.getConnectionDB().
					prepareStatement("select * from pedido");
						
			ResultSet rs = ps.executeQuery();
			pedidos = new ArrayList<Pedido>();
			
			while (rs.next()) {
				i = new Pedido();
				
				i.setId(rs.getInt(1));
				i.setData_criacao(rs.getDate(2));
				i.setStatus(rs.getString(3));
				i.setConta_id(rs.getInt(4));
				pedidos.add(i);
			}
		} catch (Exception e) {}
		
		return pedidos;
	}
	
	protected int delete(int id) {
		PreparedStatement ps;
		int count = 0;
		
		try {
			ps = DataBase.getConnectionDB().prepareStatement("delete from pedido where id=?");
			
			ps.setInt(1, id);
			count = ps.executeUpdate();
			
		} catch (Exception e) { }
		
		return count;
		
	}

}